﻿using AbpProjectTemplate.Components.Identity;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading.Tasks;

namespace AbpProjectTemplate.Web.Authentication
{
    /// <summary>
    /// 【中间件】用于验证用户登录令牌是否已过期的
    /// </summary>
    public class SecurityStampVerificationMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly SignInManager _signInManager;
        public SecurityStampVerificationMiddleware(RequestDelegate next, SignInManager _signInManager)
        {
            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }
            this._next = next;
            this._signInManager = _signInManager;
        }

        public async Task Invoke(HttpContext context)
        {
            if (context.User.Identity?.IsAuthenticated == true)
            {
                var user = await this._signInManager.ValidateSecurityStampAsync(context.User);
                if (user == null)
                    context.User = null;
            }

            await this._next(context);
        }
    }
}
